<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Constants\SuccessCode;
use Firstphp\Ip2region\Ip2Region;
use Hyperf\Contract\SessionInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\View\RenderInterface;
use Psr\Container\ContainerInterface;

abstract class AbstractController
{
    #[Inject]
    protected ContainerInterface $container;

    #[Inject]
    protected RequestInterface $request;

    #[Inject]
    protected ResponseInterface $response;

    #[Inject]
    protected RenderInterface $render;

    #[Inject]
    protected SessionInterface $session;

    #[Inject]
    protected Ip2Region $ip2region;

    public function __construct()
    {
    }

    protected function success(mixed $data = [], string|int|null $message = null, int $count = 0): \Psr\Http\Message\ResponseInterface
    {
        if (empty($message)){
            $message=SuccessCode::getMessage(SuccessCode::SERVER_SUCCESS);
        }
        if (is_int($message)){
            $message=ErrorCode::getMessage($message);
        }
        return $this->response->json(['code' => SuccessCode::SERVER_SUCCESS, 'data' => $data, 'msg' => $message, 'count' => $count]);
    }

    protected function error(string|int|null $message = null, mixed $data = []): \Psr\Http\Message\ResponseInterface
    {
        if (empty($message)){
            $message=ErrorCode::getMessage(ErrorCode::SERVER_ERROR);
        }
        if (is_int($message)){
            $message=ErrorCode::getMessage($message);
        }
        return $this->response->json(['code' => ErrorCode::SERVER_ERROR, 'data' => $data, 'msg' => $message]);
    }

    protected function json(int $code, string $msg = 'ok', array $data = [], int $count = 0): \Psr\Http\Message\ResponseInterface
    {
        return $this->response->json(['code' => $code, 'data' => $data, 'msg' => $msg, 'count' => $count]);
    }

    protected function success_xml(mixed $data = [], ?string $message = null): \Psr\Http\Message\ResponseInterface
    {
        return $this->response->xml(['code' => SuccessCode::SERVER_SUCCESS, 'data' => $data, 'msg' => $message]);
    }

    protected function error_xml(?string $message = null, mixed $data = []): \Psr\Http\Message\ResponseInterface
    {
        return $this->response->xml(['code' => ErrorCode::SERVER_ERROR, 'data' => $data, 'msg' => $message]);
    }
}
